import { MessageEntity } from './../entities/sys/message.entity';
import { SubscribeMessage, WebSocketGateway, WebSocketServer, WsResponse, OnGatewayInit, OnGatewayDisconnect,
  OnGatewayConnection } from '@nestjs/websockets';
import { Server } from 'ws';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { MessageRep } from './dto/message.rep.dto';
import { Socket } from 'socket.io';
import { Logger } from '@nestjs/common';

@WebSocketGateway(6060)
export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect{
  constructor(
    @InjectRepository(MessageEntity)
    private readonly messageRepository: Repository<MessageEntity>,
  ) {}

  @WebSocketServer()
  server: Server;

  @SubscribeMessage('msgToServer')
  public handleMessage(client: Socket, payload: any): Promise<WsResponse<any>> {
    return this.server.to(payload.room).emit('msgToClient', payload);
  }

  @SubscribeMessage('joinRoom')
  public joinRoom(client: Socket, room: string): void {
    client.join(room);
    client.emit('joinedRoom', room);
  }

  @SubscribeMessage('leaveRoom')
  public leaveRoom(client: Socket, room: string): void {
    client.leave(room);
    client.emit('leftRoom', room);
  }

  public afterInit(server: Server): void {
    return Logger.log('Init');
  }

  public handleDisconnect(client: Socket): void {
    return Logger.log(`Client disconnected: ${client.id}`);
  }

  public handleConnection(client: Socket): void {
    return Logger.log(`Client connected: ${client.id}`);
  }
}
